/*
 ============================================================================
 Name        : util.c
 Author      : Ana Roig & Pablo Abad
 Version     : 1.0
 Description : Utilidades varias compartidas
 ============================================================================
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include "util.h"

void calculateHash(unsigned char result[SHA_DIGEST_LENGTH], char *message) {
    SHA_CTX c;

    SHA1_Init(&c);
    SHA1_Update(&c, message, strlen(message));
    SHA1_Final(result, &c);
}

/*
 * Convierte de un buffer de bytes a un string con la representacion
 * hexadecimal. dest debe tener al menos 2*size+1 bytes de longitud
 */
void byte2hex(char *dest, unsigned char *source, int size) {
	char *current = dest;
	while(size-- > 0) {
		sprintf(current, "%02x", *source++);
		current += 2;
	}
}

void hex2byte(unsigned char *dest, char *source, int size) {
	while(size-- > 0) {
		unsigned int num;
		sscanf(source, "%2X", &num);
		*dest++ = (unsigned char)num;
		source += 2;
	}
}

FILE* safefopen(char *name, char *mode) {
	FILE *file;
	if ((file = fopen(name , mode)) == NULL) {
		printf("No se pudo abrir el archivo %s: %s", name, strerror(errno));
		exit(1);
	}
	return file;
}
